@import '../../js/utility.js'

// Sketch Enumerate
/**
* Enumerate text using range from 1 to number of items
* Contributors: Andrei Shapiro, Ale Muñoz, Matt McManus
*/

function toJSArray(a) {
  var len = a.count(),
      res = [];
  while(len--){
    res.push(a[len]);
  }
  return res;
}

function onRun(context){
    var selection = context.selection;

    function comparePosition(a, b){
        var THRESHOLD = 5; // allowable shift of text layer from ideal structures position
        var ydiff = b.absoluteRect().y() - a.absoluteRect().y();
        var xdiff = b.absoluteRect().x()) - a.absoluteRect().x();

        if (ydiff > THRESHOLD) return -1;
        if (ydiff < -THRESHOLD) return 1;
        if (xdiff > THRESHOLD) return -1;
        if (xdiff < -THRESHOLD) return 1;
        return 0;
    }

    function isGroup(layer) {
        return [layer isMemberOfClass:[MSLayerGroup class]] || [layer isMemberOfClass:[MSArtboardGroup class]]
    }

    function isText(layer) {
        return [layer isMemberOfClass:[MSTextLayer class]]
    }

    function collectChildren(layers, sel) {
        for (var x = 0; x < [layers count]; x++){
            var childLayer = layers.array()[x];
            if (isText(childLayer)) sel.push(childLayer); // process only text layers
        }
    }


    var newSelection = [];

    // look through selection to lookup inside groups and gather layers
    var loop = [selection objectEnumerator]
    while (layer = [loop nextObject]) {
        if (isGroup(layer)) {
            collectChildren([layer layers], newSelection);
        } else {
            if (isText(layer)) newSelection.push(layer);  // process only text layers
        }
    }

    var itemsNumber = newSelection.length;
    var selSorted = newSelection.sort(comparePosition);

    for (var i = 0; i < itemsNumber; i++) {
        var layer = selSorted[i];
        var value = (i + 1).toString();
        layer.name = layer.absoluteRect().x() + ", " + layer.absoluteRect().y();//value;
        layer.setStringValue(value);
        layer.adjustFrameToFit(); //TODO: maintain  adjustability even if user pressed Fixed. Any idea?
    }

    tools.checkPluginUpdate();
}
